package com.learn.arr;

import java.util.HashMap;

/**
 * 求数组中子数组和为sum的最长子数组长度,数组有正负0
 *
 * @Author: huangzhigao
 * @Date: 2022/2/8 20:50
 */
public class LongestSumSubArr {
    public int getRes(int[] arr, int sum) {
        //key为累加和，value为最早出现该累加和的位置
        HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
        //累加和为0的最早出现在-1位置
        map.put(0, -1);
        int tmpSum = 0;
        int length = 0;
        for (int i = 0; i < arr.length; i++) {
            tmpSum += arr[i];  //0~i的累加和
            if (map.containsKey(tmpSum - sum)) {
                Math.max(length, i - map.get(tmpSum - sum));
            }
            if (!map.containsKey(tmpSum)) {
                map.put(tmpSum, i);
            }
        }


        return length;

    }

}
